window.onload = function () {
	const canvas = document.getElementsByTagName('canvas')[0];
	const cw = canvas.width = window.innerWidth;
	const ch = canvas.height = window.innerHeight;
	const ctx = canvas.getContext('2d');
	const drops = [];

	// 取得范围内的随机数
	const random = (min, max) => Math.random() * (max - min) + min;

	// 取得随机颜色
	const ranColor = () => `#${(Math.random()*0xffffff<<0).toString(16)}`;

	// 取得十六进制转为rgba的颜色值
	const rgbaColor = (sColor, alpha) => {
		const sColorChange = [];
		sColor = sColor.toLowerCase();      	  
    	for(let i = 1; i < 7; i += 2){  
        	sColorChange.push(parseInt(`0x${sColor.slice(i,i + 2)}`));    
    	}  
    	return `rgba(${sColorChange.join(',')},${alpha})`;   
	};

	// 雨滴
	class Drop {
		constructor() {
			this.init();
		}

		init() {
			this.x = random(100, cw - 100);			// 起始点x坐标
			this.y = random(50, 150);				// 起始点y坐标
			this.vy = random(4, 8);					// y增加的速率
			this.my = random(0.6 * ch, 0.7 * ch);	// y的最大值
			this.r = 1.2;							// 圆的初始半径r
			this.vr = 1;							// r增加的速率
			this.a = 1;								// 初始透明度a
			this.va = 0.96;							// a*va透明加强
		}

		draw() {
			if (this.y < this.my) {			
				ctx.beginPath();
				ctx.fillStyle = ranColor();
				ctx.fillRect(this.x, this.y, 2, 10);
			}
			else {
				ctx.beginPath();
				ctx.strokeStyle = rgbaColor(ranColor(), this.a);
				ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
				ctx.stroke();						
			}
		}

		update() {
			if (this.y < this.my) {
				this.y += this.vy;
			}
			else {
				if (this.a > 0.03) {
					this.r += this.vr;
					if (this.r > 60) {
						this.a *= this.va;
					}
				}
				else {
					this.init();
				}				
			}
		}
	}

	// 创造雨滴
	for (let i = 0; i < 25; i ++) {
		setTimeout(() => {
			drops.push(new Drop());
		}, i * 300);
	}	
	
	// 动画开始
	function start() {
		ctx.fillStyle = 'rgba(0,0,0,0.1)';			// 透明遮罩层，覆盖旧的下落轨迹，产生拉长和模糊的效果
		ctx.fillRect(0, 0, cw, ch);
		drops.forEach(drop => {
			drop.draw();
			drop.update();	
		});		
		requestAnimationFrame(start);
	}
	start();
};